<template>
  <div class="inventory-count-page">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-input 
        v-model="searchForm.transferOrderNo" 
        placeholder="请输入调拨单号" 
        prefix-icon="el-icon-search" 
        style="width: 200px; margin-right: 10px;"
      />
      <el-select 
        v-model="searchForm.transferType" 
        placeholder="请选择调拨类型" 
        style="width: 180px; margin-right: 10px;"
      >
        <el-option label="全部" value="" />
        <el-option label="内部调拨" value="内部调拨" />
        <el-option label="库存调拨" value="库存调拨" />
        <el-option label="库存预警" value="库存预警" />
        <el-option label="满仓调离" value="满仓调离" />
        <el-option label="其他调拨" value="其他调拨" />
      </el-select>
      <el-select 
        v-model="searchForm.outWarehouseId" 
        placeholder="请选择调出仓库" 
        style="width: 180px; margin-right: 10px;"
      >
        <el-option label="全部" value="" />
        <el-option 
          v-for="warehouse in warehouseList" 
          :key="warehouse.id" 
          :label="warehouse.name" 
          :value="warehouse.id" 
        />
      </el-select>
      <el-select 
        v-model="searchForm.inWarehouseId" 
        placeholder="请选择调入仓库" 
        style="width: 180px; margin-right: 10px;"
      >
        <el-option label="全部" value="" />
        <el-option 
          v-for="warehouse in warehouseList" 
          :key="warehouse.id" 
          :label="warehouse.name" 
          :value="warehouse.id" 
        />
      </el-select>
      <el-select 
        v-model="searchForm.orderStatus" 
        placeholder="请选择单据状态" 
        style="width: 180px; margin-right: 10px;"
      >
        <el-option label="全部" value="" />
        <el-option label="待审核" value="待审核" />
        <el-option label="已审核" value="已审核" />
        <el-option label="已完成" value="已完成" />
        <el-option label="已取消" value="已取消" />
      </el-select>
      <el-date-picker
        v-model="searchForm.startTime"
        type="date"
        placeholder="申请开始时间"
        style="width: 180px; margin-right: 10px;"
      />
      <el-date-picker
        v-model="searchForm.endTime"
        type="date"
        placeholder="申请结束时间"
        style="width: 180px; margin-right: 10px;"
      />
      <el-input 
        v-model="searchForm.creator" 
        placeholder="请输入制单人" 
        style="width: 180px; margin-right: 10px;"
      />
      <el-button @click="resetSearch">重置</el-button>
      <el-button type="primary" @click="search">查询</el-button>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-buttons">
      <el-button type="primary" @click="add()">新增</el-button>
      <el-button @click="handleDelete" :disabled="!selectedRows.length">删除</el-button>
      <el-button @click="handleExport">导出</el-button>
      <el-button @click="handleCancelOrder" :disabled="!selectedRows.length">作废</el-button>
      <el-button @click="refresh">刷新</el-button>
    </div>

    <!-- 表格区域 -->
    <el-table 
      v-loading="loading" 
      :data="tableData" 
      border 
      style="width: 100%; margin-top: 10px;"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="序号" type="index" width="50" />
      <el-table-column prop="TransferOrderNo" label="调拨单号" width="160" show-overflow-tooltip>
        <template #default="{ row }">
          <el-button type="text" text-color="#409EFF" @click="viewDetails(row.TransferOrderNo)">{{ row.TransferOrderNo }}</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="OrderStatus" label="单据状态" width="100" />
      <el-table-column prop="TransferType" label="调拨类型" width="100" />
      <el-table-column prop="OutWarehouseName" label="调出仓库" width="120" />
      <el-table-column prop="InWarehouseName" label="调入仓库" width="120" />
      <el-table-column prop="Creator" label="制单人" width="100" />
      <!-- 部门列已移除 -->
      <el-table-column prop="Handler" label="经办人" width="100" />
      <el-table-column prop="ApplyDate" label="申请日期" width="140" :formatter="formatDate" />
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button type="text" text-color="#409EFF" @click="edit(row.TransferOrderNo)">编辑</el-button>
          <el-button type="text" text-color="#F56C6C" @click="deleteRow(row.TransferOrderNo)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination">
      <el-pagination
        layout="total, prev, pager, next, jumper"
        :total="total"
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        style="margin-top: 20px;"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 调拨单详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="调拨单详情"
      width="80%"
      destroy-on-close
    >
      <div v-if="detailLoading" class="loading-container">
        <el-skeleton :rows="6" animated />
      </div>
      <div v-else-if="orderDetails.length > 0">
        <el-card class="mb-4">
          <template #header>
            <div class="card-header">
              <span>调拨单信息</span>
            </div>
          </template>
          <div class="detail-info">
            <div class="info-item">
              <span class="info-label">调拨单号：</span>
              <span class="info-value">{{ currentOrderDetail?.TransferOrderNo || '' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">调拨类型：</span>
              <span class="info-value">{{ currentOrderDetail?.TransferType || '' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">调出仓库：</span>
              <span class="info-value">{{ currentOrderDetail?.OutWarehouseName || '' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">调入仓库：</span>
              <span class="info-value">{{ currentOrderDetail?.InWarehouseName || '' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">制单人：</span>
              <span class="info-value">{{ currentOrderDetail?.Creator || '' }}</span>
            </div>
            <!-- 部门信息已移除 -->
            <div class="info-item">
              <span class="info-label">经办人：</span>
              <span class="info-value">{{ currentOrderDetail?.Handler || '' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">申请日期：</span>
              <span class="info-value">{{ formatDate(currentOrderDetail?.ApplyDate) }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">单据状态：</span>
              <span class="info-value">{{ currentOrderDetail?.OrderStatus || '' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">备注：</span>
              <span class="info-value">{{ currentOrderDetail?.Remark || '' }}</span>
            </div>
          </div>
        </el-card>
        
        <el-card>
          <template #header>
            <div class="card-header">
              <span>调拨明细</span>
            </div>
          </template>
          <el-table :data="orderDetails" border style="width: 100%">
            <el-table-column prop="ProductNo" label="产品编号" width="120" />
            <el-table-column prop="ProductName" label="产品名称" width="200" show-overflow-tooltip />
            <el-table-column prop="Spec" label="规格" width="150" />
            <el-table-column prop="Unit" label="单位" width="100" />
            <el-table-column prop="ProductType" label="产品类型" width="120" />
            <el-table-column prop="TransferQty" label="调拨数量" width="100" />
            <el-table-column prop="UnitPrice" label="单价" width="100" :formatter="formatCurrency" />
            <el-table-column prop="TransferAmount" label="金额" width="120" :formatter="formatCurrency" />
          </el-table>
        </el-card>
      </div>
      <div v-else>
        <div class="empty-detail">暂无明细数据</div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import http from '@/api/http';
const router = useRouter();

// 搜索表单数据
const searchForm = reactive({
  transferOrderNo: '',
  transferType: '',
  outWarehouseId: '',
  inWarehouseId: '',
  orderStatus: '',
  startTime: '',
  endTime: '',
  creator: ''
});

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10
});

// 表格数据
const tableData = ref([]);
const total = ref(0);
const loading = ref(false);
const selectedRows = ref([]);
const warehouseList = ref([]);

// 详情对话框相关
const detailDialogVisible = ref(false);
const detailLoading = ref(false);
const orderDetails = ref([]);
const currentOrderDetail = ref(null);

// 获取调拨单列表
const fetchTransferOrderList = async () => {
  loading.value = true;
  try {
    // 构建查询参数 - 使用 POST 方法时参数格式
    const params = {
      page: pagination.currentPage - 1, // 后端从0开始计数
      rows: pagination.pageSize,
      sort: 'TransferOrderNo',
      order: 'desc'
    };
    
    // 添加搜索条件到 wheres 参数
    if (searchForm.transferOrderNo) {
      params.wheres = params.wheres || [];
      params.wheres.push({ name: 'TransferOrderNo', value: searchForm.transferOrderNo });
    }
    if (searchForm.transferType) {
      params.wheres = params.wheres || [];
      params.wheres.push({ name: 'TransferType', value: searchForm.transferType });
    }
    if (searchForm.outWarehouseId) {
      params.wheres = params.wheres || [];
      params.wheres.push({ name: 'OutWarehouseId', value: searchForm.outWarehouseId });
    }
    if (searchForm.inWarehouseId) {
      params.wheres = params.wheres || [];
      params.wheres.push({ name: 'InWarehouseId', value: searchForm.inWarehouseId });
    }
    if (searchForm.orderStatus) {
      params.wheres = params.wheres || [];
      params.wheres.push({ name: 'OrderStatus', value: searchForm.orderStatus });
    }
    if (searchForm.creator) {
      params.wheres = params.wheres || [];
      params.wheres.push({ name: 'Creator', value: searchForm.creator, displayType: 'like' });
    }
    if (searchForm.startTime) {
      params.wheres = params.wheres || [];
      params.wheres.push({ name: 'ApplyDate', value: searchForm.startTime, displayType: 'gte' });
    }
    if (searchForm.endTime) {
      params.wheres = params.wheres || [];
      params.wheres.push({ name: 'ApplyDate', value: searchForm.endTime, displayType: 'lte' });
    }
    
    const response = await http.post('/api/transferorder/GetPageData', params, false);
    
    console.log('调拨单列表API响应:', response); // 调试日志
    
    // 检查响应是否成功 - 兼容多种成功标识
    const isSuccess = response && (
      response.success === true || 
      response.status === 0 || 
      response.status === true || 
      response.status === 1 ||
      response.code === 200
    );
    
    if (isSuccess) {
      // 处理 GetPageData 返回的数据格式
      let rows = [];
      let totalCount = 0;
      
      // GetPageData 返回格式：response.rows 和 response.total
      if (response.rows && Array.isArray(response.rows)) {
        rows = response.rows;
        totalCount = response.total || 0;
      } else if (response.data && response.data.rows) {
        rows = response.data.rows;
        totalCount = response.data.total || 0;
      } else if (Array.isArray(response.data)) {
        rows = response.data;
        totalCount = rows.length;
      } else if (Array.isArray(response)) {
        rows = response;
        totalCount = rows.length;
      }
      
      // 转换API返回的数据格式为表格需要的格式
      // 注意：后端返回的字段名可能是大写开头（PascalCase）
      tableData.value = rows.map(item => ({
        TransferOrderNo: item.TransferOrderNo || item.transferOrderNo,
        Creator: item.Creator || item.creator,
        TransferType: item.TransferType || item.transferType,
        ApplyDate: item.ApplyDate || item.applyDate,
        OutWarehouseId: item.OutWarehouseId || item.outWarehouseId,
        InWarehouseId: item.InWarehouseId || item.inWarehouseId,
        InWarehouseName: item.InWarehouseName || item.inWarehouseName || '未知',
        OutWarehouseName: item.OutWarehouseName || item.outWarehouseName || '未知',
        Handler: item.Handler || item.handler,
        Remark: item.Remark || item.remark,
        OrderStatus: item.OrderStatus || item.orderStatus,
        CreateTime: item.CreateTime || item.createTime,
        OutStatus: item.OutStatus || item.outStatus,
        InStatus: item.InStatus || item.inStatus
      }));
      total.value = totalCount;
    } else {
      console.error('API响应格式不正确:', response);
      ElMessage.error(response?.message || '获取调拨单列表失败');
      tableData.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('获取调拨单列表失败:', error);
    
    // 如果主 API 失败，尝试使用带 model 后缀的备用 API
    if (error.response && error.response.status === 404) {
      try {
        console.log('尝试备用API: /api/transferordermodel/GetPageData');
        const params = {
          page: pagination.currentPage - 1,
          rows: pagination.pageSize,
          sort: 'TransferOrderNo',
          order: 'desc'
        };
        
        const fallbackResponse = await http.post('/api/transferordermodel/GetPageData', params, false);
        console.log('备用API响应:', fallbackResponse);
        
        const isSuccess = fallbackResponse && (
          fallbackResponse.success === true || 
          fallbackResponse.status === 0 || 
          fallbackResponse.status === true || 
          fallbackResponse.status === 1 ||
          fallbackResponse.code === 200
        );
        
        if (isSuccess && fallbackResponse.rows) {
          tableData.value = fallbackResponse.rows.map(item => ({
            TransferOrderNo: item.TransferOrderNo || item.transferOrderNo,
            Creator: item.Creator || item.creator,
            TransferType: item.TransferType || item.transferType,
            ApplyDate: item.ApplyDate || item.applyDate,
            OutWarehouseId: item.OutWarehouseId || item.outWarehouseId,
            InWarehouseId: item.InWarehouseId || item.inWarehouseId,
            InWarehouseName: item.InWarehouseName || item.inWarehouseName || '未知',
            OutWarehouseName: item.OutWarehouseName || item.outWarehouseName || '未知',
            Handler: item.Handler || item.handler,
            Remark: item.Remark || item.remark,
            OrderStatus: item.OrderStatus || item.orderStatus,
            CreateTime: item.CreateTime || item.createTime,
            OutStatus: item.OutStatus || item.outStatus,
            InStatus: item.InStatus || item.inStatus
          }));
          total.value = fallbackResponse.total || 0;
          loading.value = false;
          return; // 成功则退出
        }
      } catch (fallbackError) {
        console.error('备用API也失败了:', fallbackError);
      }
    }
    
    // 所有 API 都失败时显示错误
    if (error.response) {
      ElMessage.error(`服务器错误: ${error.response.status} - ${error.response.statusText || '请重试'}`);
    } else if (error.request) {
      ElMessage.error('网络请求失败，请检查网络连接');
    } else {
      ElMessage.error('获取调拨单列表失败，请重试');
    }
    tableData.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 获取仓库列表
const fetchWarehouseList = async () => {
  try {
    // 使用正确的仓库API（POST请求）
    const response = await http.post('/api/warehousemodel/GetPageData', {
      pageIndex: 1,
      pageSize: 1000
    }, false);
    
    if (response && (response.status === 0 || response.status === true || response.status === 1)) {
      let data = [];
      
      // 处理不同的数据格式
      if (response.rows && Array.isArray(response.rows)) {
        data = response.rows;
      } else if (response.data?.rows && Array.isArray(response.data.rows)) {
        data = response.data.rows;
      } else if (Array.isArray(response.data)) {
        data = response.data;
      }
      
      // 转换数据格式
      warehouseList.value = data.map(item => ({
        id: item.Id || item.id,
        name: item.WarehouseName || item.warehouseName || item.name
      })).filter(item => item.id && item.name);
      
      // 如果没有获取到仓库数据，使用默认数据
      if (warehouseList.value.length === 0) {
        warehouseList.value = [
          { id: 1, name: '货品仓库一' },
          { id: 2, name: '货品仓库二' }
        ];
      }
    } else {
      // 如果API调用失败，使用默认数据
      warehouseList.value = [
        { id: 1, name: '货品仓库一' },
        { id: 2, name: '货品仓库二' }
      ];
    }
  } catch (error) {
    console.error('获取仓库列表失败:', error);
    // 出错时使用默认数据
    warehouseList.value = [
      { id: 1, name: '货品仓库一' },
      { id: 2, name: '货品仓库二' }
    ];
  }
};

// 查看调拨单详情
const viewDetails = async (transferOrderNo) => {
  if (!transferOrderNo) {
    ElMessage.warning('调拨单号不能为空');
    return;
  }
  
  detailDialogVisible.value = true;
  detailLoading.value = true;
  
  try {
    const response = await http.get(`/api/transferorder/GetDetails/${transferOrderNo}`, {}, false);
    
    console.log('调拨单详情API响应:', response); // 调试日志
    
    // 检查响应是否成功 - 兼容多种成功标识
    const isSuccess = response && (
      response.success === true || 
      response.status === 0 || 
      response.status === true || 
      response.status === 1 ||
      response.code === 200
    );
    
    if (isSuccess) {
      // 处理不同的数据格式
      if (response.data) {
        orderDetails.value = Array.isArray(response.data) ? response.data : [response.data];
      } else if (Array.isArray(response)) {
        orderDetails.value = response;
      } else {
        orderDetails.value = [];
      }
      
      // 如果有明细数据，保存当前订单信息
      if (orderDetails.value.length > 0) {
        // 查找当前订单在表格数据中的完整信息
        currentOrderDetail.value = tableData.value.find(item => item.TransferOrderNo === transferOrderNo) || {
          TransferOrderNo: transferOrderNo
        };
      }
    } else {
      ElMessage.error(response?.message || '获取调拨单详情失败');
      orderDetails.value = [];
    }
  } catch (error) {
    console.error('获取调拨单详情失败:', error);
    if (error.response) {
      ElMessage.error(`服务器错误: ${error.response.status} - ${error.response.statusText || '请重试'}`);
    } else if (error.request) {
      ElMessage.error('网络请求失败，请检查网络连接');
    } else {
      ElMessage.error('获取调拨单详情失败，请重试');
    }
    orderDetails.value = [];
  } finally {
    detailLoading.value = false;
  }
};

// 搜索
const search = () => {
  pagination.currentPage = 1;
  fetchTransferOrderList();
};

// 重置搜索条件
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = '';
  });
};

// 刷新
const refresh = () => {
  fetchTransferOrderList();
};

// 新增
const add = () => {
  router.push('/transferorderItem');
};

// 编辑
const edit = (transferOrderNo) => {
  router.push({ path: '/transferorderItem', query: { id: transferOrderNo } });
};

// 删除单行
const deleteRow = async (transferOrderNo) => {
  try {
    // 这里应该调用删除API
    ElMessage.success('删除成功');
    fetchTransferOrderList();
  } catch (error) {
    console.error('删除失败:', error);
    ElMessage.error('删除失败，请重试');
  }
};

// 批量删除
const handleDelete = async () => {
  try {
    // 这里应该调用批量删除API
    ElMessage.success('批量删除成功');
    fetchTransferOrderList();
  } catch (error) {
    console.error('批量删除失败:', error);
    ElMessage.error('批量删除失败，请重试');
  }
};

// 导出
const handleExport = () => {
  ElMessage.success('导出功能开发中');
};

// 作废订单
const handleCancelOrder = () => {
  ElMessage.success('作废功能开发中');
};

// 处理选择变化
const handleSelectionChange = (val) => {
  selectedRows.value = val;
};

// 处理分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  fetchTransferOrderList();
};

// 处理页码变化
const handleCurrentChange = (current) => {
  pagination.currentPage = current;
  fetchTransferOrderList();
};

// 格式化日期 - 只显示年月日
const formatDate = (dateString) => {
  if (!dateString) return '';
  
  // 创建日期对象
  const date = new Date(dateString);
  
  // 检查日期是否有效
  if (isNaN(date.getTime())) {
    // 尝试处理不同格式的日期字符串
    try {
      // 处理可能的格式问题，例如ISO格式、时间戳等
      const processedDate = new Date(dateString.replace(/\//g, '-'));
      if (!isNaN(processedDate.getTime())) {
        return processedDate.toLocaleDateString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit'
        });
      }
    } catch (e) {
      console.warn('日期格式化失败:', e);
    }
    return ''; // 无效日期返回空字符串
  }
  
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  });
};

// 格式化货币
const formatCurrency = (value) => {
  if (value === null || value === undefined) return '¥0.00';
  return `¥${parseFloat(value).toFixed(2)}`;
};

// 页面挂载时加载数据
onMounted(async () => {
  await Promise.all([
    fetchWarehouseList(),
    fetchTransferOrderList()
  ]);
});
</script>

<style scoped>
.inventory-count-page {
  padding: 20px;
  background-color: #fff;
  min-height: 100vh;
}

.search-area {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  flex-wrap: wrap;
  gap: 10px;
}

.action-buttons {
  display: flex;
  gap: 10px;
  margin-bottom: 16px;
}

.pagination {
  text-align: right;
  margin-top: 20px;
}

/* 详情对话框样式 */
.mb-4 {
  margin-bottom: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.detail-info {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-top: 10px;
}

.info-item {
  width: calc(50% - 10px);
  margin-bottom: 10px;
}

.info-label {
  font-weight: 500;
  color: #606266;
  margin-right: 8px;
}

.info-value {
  color: #303133;
}

.loading-container {
  padding: 20px 0;
}

.empty-detail {
  text-align: center;
  padding: 40px 0;
  color: #909399;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .search-area {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-area > * {
    width: 100%;
    margin-right: 0 !important;
  }
  
  .info-item {
    width: 100%;
  }
}

@media (max-width: 768px) {
  .inventory-count-page {
    padding: 10px;
  }
  
  .action-buttons {
    flex-wrap: wrap;
  }
}
</style>